package edu.vu.colorsplosion;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

public class Launcher extends Activity {

    public ViewGroup _viewgroup;
    public Activity _launcher = this;
    public Handler handler = new Handler();
    public List<Animation> animList = new ArrayList<Animation>(); 
    public Animation testAnimation;
    private int hsnum = 100;
    private SoundPool sp;
    private HashMap<Integer, Integer> soundsMap;
    
    Thread _animThread;
    
    private Thread makeAnimThread(){
        return new Thread(new Runnable() {
            public void run() {
                handler.postDelayed(new Runnable() { 
                     public void run() { 
                         _runAnimation(_launcher, findViewById(R.id.star_field1)); 
                     } 
                }, 10);
            }
        });
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        setContentView(R.layout.activity_launcher);
        _viewgroup = (ViewGroup) findViewById(R.id.parentlayout);
        
        //Initialize our SoundPool and load sound(s) into the sounds map
        sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
        soundsMap = new HashMap<Integer, Integer>();
        soundsMap.put(1, sp.load(this, R.raw.laser1, 1));
        
        //Creates "Start Game" button
        Button first_button = (Button) findViewById(R.id.first_button);
        first_button.setOnClickListener(new View.OnClickListener() {
        
            public void onClick(View v)
            {
                //Play sound
                playSound(1);
                
                //Start game activity
                Intent i = new Intent(getApplicationContext(), GameWindow.class);
                startActivity(i);
            }
        });
        
        //Creates "Options" button
        Button second_button = (Button) findViewById(R.id.second_button);
        second_button.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                //UpdateHighScores(4007);
                playSound(1);//Play sound
                startActivity(new Intent(getApplicationContext(), Options.class));
            }
        });
        
        //Creates "Hi Scores" button
        Button third_button = (Button) findViewById(R.id.third_button);
        third_button.setOnClickListener(new View.OnClickListener() {
        
            public void onClick(View v) {
                playSound(1);//Play sound
                Intent i = new Intent(getApplicationContext(), HighScores.class);
                startActivity(i);
            }
        });
        
        //TranslateAnimation x = new TranslateAnimation(getApplicationContext(), null);
    }

    @Override
    public void onPause() {
        super.onPause();
        Iterator<Animation> it = animList.iterator();
        while (it.hasNext()) {
            Animation cur = it.next();
            cur.cancel();
            cur.reset();
        }
        
        if(_animThread != null) {
            Thread moribund = _animThread;
            _animThread = null;
            moribund.interrupt();
        }
    }
    
    @Override

    public void onResume() {
        super.onResume();
            /*Toast.makeText(getApplicationContext(), "THREAD IS NOT ALIVE", Toast.LENGTH_SHORT).show(); 
            _animThread = _runnable;
            _animThread.start();*/ //Broken for now
        Intent i = getIntent();
        boolean boolScoreCheck = i.getBooleanExtra("isScore", false);
        if (boolScoreCheck){
            UpdateHighScores(i.getIntExtra("score", 0));
        }
        _animThread = makeAnimThread();
        _animThread.start();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_launcher, menu);
        return true;
    }
    
    public static void setLayoutAnimation(ViewGroup panel, Context ctx) {
          LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(ctx, R.anim.slide_right);
          panel.setLayoutAnimation(controller);
    }
    
    public Animation _runAnimation(Activity ctx, View target) {
          //Animation animation = AnimationUtils.loadAnimation(ctx, android.R.anim.fade_out);
          Animation animation = AnimationUtils.loadAnimation(ctx, R.anim.slide_right);
          animation.setFillAfter(true);
          target.startAnimation(animation);
          animList.add(animation);
          return animation;
        } 

    public final void UpdateHighScores(int x) {
        SharedPreferences highscores = getApplicationContext().getSharedPreferences("highscores", MODE_WORLD_READABLE);

        /*Map<String, Integer> _scores = (Map<String, Integer>) highscores.getAll();
        int score1 = _scores.get("score1");
        int score2 = _scores.get("score2");
        int score3 = _scores.get("score3");
        int score4 = _scores.get("score4");
        int score5 = _scores.get("score5");*/ //Edited this out as I think it is slower than the other way - need to test
        
        int score1 = highscores.getInt("score1", 5000);
        int score2 = highscores.getInt("score2", 4000);
        int score3 = highscores.getInt("score3", 3000);
        int score4 = highscores.getInt("score4", 2000);
        int score5 = highscores.getInt("score5", 1000);
        
        if (x < score5){
            return;
        }
        
        String newName = "";
        
        SharedPreferences.Editor mEd = highscores.edit();
        
        String name1 = highscores.getString("name1", "Colorsplosion");
        String name2 = highscores.getString("name2", "Colorsplosion");
        String name3 = highscores.getString("name3", "Colorsplosion");
        String name4 = highscores.getString("name4", "Colorsplosion");
        String name5 = highscores.getString("name5", "Colorsplosion");
        
        if (x > score1){

            score5 = score4;
            score4 = score3;
            score3 = score2;
            score2 = score1;
            score1 = x;
            mEd.putInt("score1", score1).putInt("score2", score2).putInt("score3", score3).putInt("score4", score4).putInt("score5", score5);
            
            name5 = name4;
            name4 = name3;
            name3 = name2;
            name2 = name1;
            name1 = newName;
            mEd.putString("name1", name1).putString("name2", name2).putString("name3", name3).putString("name4", name4).putString("name5", name5);
            
            hsnum = 1;
            mEd.commit();
            doDialog();
        } else if (x > score2){
            score5 = score4;
            score4 = score3;
            score3 = score2;
            score2 = x;
            mEd.putInt("score2", score2).putInt("score3", score3).putInt("score4", score4).putInt("score5", score5);
            
            name5 = name4;
            name4 = name3;
            name3 = name2;
            name2 = newName;
            mEd.putString("name2", name2).putString("name3", name3).putString("name4", name4).putString("name5", name5);
            
            hsnum = 2;
            mEd.commit();
            doDialog();
        } else if (x > score3){
            score5 = score4;
            score4 = score3;
            score3 = x;
            mEd.putInt("score3", score3).putInt("score4", score4).putInt("score5", score5);
            
            name5 = name4;
            name4 = name3;
            name3 = newName;
            mEd.putString("name3", name3).putString("name4", name4).putString("name5", name5);
            
            hsnum = 3;
            mEd.commit();
            doDialog();
        } else if (x > score4){
            score5 = score4;
            score4 = x;
            mEd.putInt("score4", score4).putInt("score5", score5);
            
            name5 = name4;
            name4 = newName;
            mEd.putString("name4", name4).putString("name5", name5);
            
            hsnum = 4;
            mEd.commit();
            doDialog();
        } else if (x > score5){
            score5 = x;
            mEd.putInt("score5", score5);
            
            hsnum = 5;
            mEd.commit();
            doDialog();
        }
        
        return;
    }
    
    public void doDialog() {
        LayoutInflater factory = LayoutInflater.from(this); 
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        final LinearLayout tmp = (LinearLayout) factory.inflate(R.layout.highscores_dialog, null);
        dialog.setView(tmp);
        dialog.setTitle("Please enter your name:");
        dialog.setPositiveButton("Done", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                EditText name = (EditText) tmp.getChildAt(0);
                Intent i = new Intent(getApplicationContext(), HighScores.class);
                i.putExtra("name", name.getText().toString());
                i.putExtra("number", hsnum);
                startActivity(i);
            }
        });
        dialog.show();
    }
    
    public void playSound(int soundid) {
        //Use for calculating volume
        //AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        
        //Play sound
        sp.play(soundsMap.get(soundid), 1, 1, 1, 0, 1);
    }
}
